package com.yunqiao.service.api.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Dict;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yunqiao.common.consts.AppConsts;
import com.yunqiao.common.exception.CustomApiException;
import com.yunqiao.common.pay.AliPay;
import com.yunqiao.common.pay.WxPay;
import com.yunqiao.common.utils.PageUtils;
import com.yunqiao.common.utils.Query;
import com.yunqiao.service.api.OrderCashService;
import com.yunqiao.service.api.OrderService;
import com.yunqiao.service.api.entity.ApplyPartnerEntity;
import com.yunqiao.service.api.entity.OrderCashEntity;
import com.yunqiao.service.api.entity.UserEntity;
import com.yunqiao.service.api.mapper.ApplyPartnerMapper;
import com.yunqiao.service.api.mapper.OrderCashMapper;
import com.yunqiao.service.api.mapper.UserMapper;
import com.yunqiao.service.api.vo.ApplyPartnerEntityVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Date;
import java.util.Map;

/**
 * 押金订单信息
 * @company 今日速运
 * @author Crocutax
 * @email wangxw725@foxmail.com
 * @date 2019-04-11 18:54:10
 */
@Service("orderCashService")
public class OrderCashServiceImpl extends ServiceImpl<OrderCashMapper, OrderCashEntity> implements OrderCashService {

    @Resource
    private OrderCashMapper orderCashMapper;

    @Resource
    private UserMapper userMapper;
    @Resource
    private ApplyPartnerMapper applyPartnerMapper;
    @Resource
    private OrderService orderService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        //各种查询条件的过滤,在此进行
        QueryWrapper<OrderCashEntity> queryWrapper = new QueryWrapper<>();

        IPage<OrderCashEntity> page = this.page(new Query<OrderCashEntity>(params).getPage(),queryWrapper);
        return new PageUtils(page);
    }

    @Override
    public String cashPrice(Long userId, Integer type) throws Exception {
        UserEntity userEntity = userMapper.selectById(userId);
        if (userEntity.getDeposit() != null && userEntity.getDeposit().compareTo(new BigDecimal("0")) != 0) {
            throw new CustomApiException("你已经交过押金了");
        }
        //生成订单  押金
        OrderCashEntity orderCashEntity = new OrderCashEntity();
        orderCashEntity.setPrice(new BigDecimal("1000"));
        orderCashEntity.setUserId(userId);
        orderCashEntity.setState(AppConsts.ORDER_CASH_STATE_1);
        orderCashEntity.setCreateTime(new Date());
        orderCashEntity.setOrderNumber(DateUtil.format(DateUtil.date(), "yyyyMMddHHmmsss" + RandomUtil.getRandom().nextInt(0, 100000)));
        orderCashEntity.setRemark("交押金");
        orderCashEntity.setStatus(AppConsts.ORDER_CASH_STATUS_1);
        orderCashEntity.setType(type);
        orderCashMapper.insert(orderCashEntity);

        if (type.equals(AppConsts.PAY_TYPE_1)) {
            //支付宝支付
            return AliPay.pay("交押金", orderCashEntity.getOrderNumber(), orderCashEntity.getPrice().toString(), userEntity.getRoleType());
        } else if (type.equals(AppConsts.PAY_TYPE_2)) {
            return WxPay.pay("支付押金", orderCashEntity.getOrderNumber(), orderCashEntity.getPrice().toString(), userEntity.getRoleType());
        } else if (type.equals(AppConsts.PAY_TYPE_3)) {
            int i = 0;
            do {
                userEntity = userMapper.selectById(userEntity.getId());
                if (userEntity.getBalance().doubleValue() < orderCashEntity.getPrice().doubleValue()) {
                    throw new CustomApiException("您的余额不足");
                }
                i = userMapper.updateBalance(userEntity.getId(), userEntity.getBalance().subtract(orderCashEntity.getPrice()), userEntity.getBlockBalance(), userEntity.getVersion());
            } while (i == 0);
            orderService.aliPaySuccess(orderCashEntity.getOrderNumber());
            return "支付成功";
        }
        return null;
    }



    @Override
    public String PayingCommission(ApplyPartnerEntityVo applyPartnerEntity) throws Exception {
        ApplyPartnerEntity applyPartner = applyPartnerMapper.selectById(applyPartnerEntity.getId());
        OrderCashEntity orderCashEntity = new OrderCashEntity();
        orderCashEntity.setOrderNumber(DateUtil.format(DateUtil.date(), "yyyyMMddHHmmsss" + RandomUtil.getRandom().nextInt(0, 100000)));
        orderCashEntity.setStatus(AppConsts.ORDER_CASH_STATUS_1);
        orderCashEntity.setState(AppConsts.ORDER_CASH_STATE_2);
        orderCashEntity.setRemark("支付代理费");
        orderCashEntity.setTargetId(applyPartner.getId());
        orderCashEntity.setUserId(applyPartner.getUserId());
        orderCashEntity.setPrice(applyPartner.getMoneyDeposit().add(applyPartner.getMoneyFee()));
        orderCashMapper.insert(orderCashEntity);

        UserEntity userEntity = userMapper.selectById(applyPartner.getUserId());
        if (applyPartnerEntity.getPayType().equals(AppConsts.PAY_TYPE_1)) {
            //支付宝支付
            return AliPay.pay("支付代理费", orderCashEntity.getOrderNumber(),orderCashEntity.getPrice().toString(), userEntity.getRoleType());
        } else if (applyPartnerEntity.getPayType().equals(AppConsts.PAY_TYPE_2)) {
            //微信支付
            return WxPay.pay("支付代理费", orderCashEntity.getOrderNumber(),orderCashEntity.getPrice().toString(), userEntity.getRoleType());
        } else if (applyPartnerEntity.getPayType().equals(AppConsts.PAY_TYPE_4)) {
            //微信小程序支付
            return WxPay.payJSAPI("支付代理费", orderCashEntity.getOrderNumber(),orderCashEntity.getPrice().toString(), userEntity.getRoleType(),userEntity.getWxCloudOpenid());
        }else if (applyPartnerEntity.getPayType().equals(AppConsts.PAY_TYPE_3)) {
            //钱包支付
            int i = 0;
            do {
                userEntity = userMapper.selectById(userEntity.getId());
                if (userEntity.getBalance().doubleValue() < orderCashEntity.getPrice().doubleValue()) {
                    throw new CustomApiException("您的余额不足");
                }
                i = userMapper.updateBalance(userEntity.getId(), userEntity.getBalance().subtract(orderCashEntity.getPrice()), userEntity.getBlockBalance(), userEntity.getVersion());
            } while (i == 0);
            // 付代理费
            orderService.aliPaySuccess(orderCashEntity.getOrderNumber());
            return "支付成功";
        }
        return null;
    }

    @Override
    public String reCharge(OrderCashEntity orderCashEntity,Integer payType,String openId) throws Exception {
        if (orderCashEntity.getType() == null || orderCashEntity.getPrice() == null || orderCashEntity.getUserId() == null) {
            throw new CustomApiException("参数有误");
        }
        orderCashEntity.setOrderNumber(DateUtil.format(DateUtil.date(), "yyyyMMddHHmmsss" + RandomUtil.getRandom().nextInt(0, 100000)));
        orderCashEntity.setStatus(AppConsts.ORDER_CASH_STATUS_1);
        orderCashEntity.setState(AppConsts.ORDER_CASH_STATE_3);
        orderCashEntity.setRemark("充值");
        orderCashEntity.setTargetId(orderCashEntity.getUserId());
        orderCashEntity.setUserId(orderCashEntity.getUserId());
        orderCashMapper.insert(orderCashEntity);

        UserEntity userEntity = userMapper.selectById(orderCashEntity.getUserId());
        if (orderCashEntity.getType().equals(AppConsts.PAY_TYPE_1)) {
            //支付宝支付
            return AliPay.pay("充值", orderCashEntity.getOrderNumber(),orderCashEntity.getPrice().toString(), userEntity.getRoleType());
        } else if (orderCashEntity.getType().equals(AppConsts.PAY_TYPE_2)) {
            //微信支付
            if(!org.springframework.util.StringUtils.isEmpty(payType)&&payType==1){
                //微信小程序支付
                return WxPay.payJSAPI("用户下单", orderCashEntity.getOrderNumber(), orderCashEntity.getPrice().toString(), userEntity.getRoleType(),openId);
            }
            return WxPay.pay("充值", orderCashEntity.getOrderNumber(),orderCashEntity.getPrice().toString(), userEntity.getRoleType());
        }

        return null;
    }

    @Override
    public Dict getFiducialPoint(Long userId) {
        return this.orderService.getFiducialPoint(userId);
    }
}
